package cn.wgx.module.mind.service;

import cn.wgx.common.base.IBaseMapper;
import cn.wgx.common.base.IBaseService;
import cn.wgx.common.entity.mind.MindBaseEntity;
import cn.wgx.common.util.ReflectionUtils;
import com.baomidou.mybatisplus.annotation.TableId;

import java.lang.reflect.Field;
import java.util.List;

public abstract class BaseMindService<M extends IBaseMapper<T>, T extends MindBaseEntity>
        extends IBaseService<M, T> {

    public Integer getProIdById(Integer id){
        T t = baseMapper.selectById(id);
        return t==null?null:t.getPro_id();
    }


    public Integer getProIdByT(T t){
//        Field[] fields = t.getClass().getDeclaredFields();
        List<Field> fields = ReflectionUtils.getAllFields(t.getClass());
        Integer pro_id = null;
        for(Field field: fields){
            if(field.getName().equals("pro_id")){
                field.setAccessible(true);
                try {
                    Object o = field.get(t);
                    if(o instanceof Integer){
                        pro_id = (Integer)o;
                        return pro_id;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                continue;
            }
            TableId annotation = field.getAnnotation(TableId.class);
            if(annotation == null){
                continue;
            }
            //根据主键查找pro_id
            field.setAccessible(true);
            try {
                Object o = field.get(t);
                if(o instanceof Integer){
                    return getProIdById((Integer)o);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return pro_id;
    }
}
